<template>
  <div class="page_main">
    <canvas ref="cavs" width="800" height="600"></canvas>
  </div>

</template>

<script>
export default {
  name: 'canvasTest',
  data() {
    return {
      msg: '3'
    }
  },
  mounted() {
    let canvas = this.$refs.cavs
    let ctx = canvas.getContext('2d')

    let ballV = 1
    let R = 100
    let ballR = 10
    ctx.lineWidth = 3
    ctx.strokeStyle = 'red'

    function initBall() {
      let ball = []
      for (let i = 0; i < 9; i++) {
        let obj = {}
        obj.y = R * Math.sin((i * Math.PI) / 9)
        obj.x = 0
        obj.v = 1
        ball.push(obj)
      }
      return ball
    }

    window.balls = initBall()

    // 中心点
    let center = {
      x: canvas.width / 2,
      y: canvas.height / 2
    }
    ctx.translate(center.x, center.y)

    function drawSinLine(deg, i) {
      ctx.clearRect(-canvas.width, -canvas.height, canvas.width * 2, canvas.height * 2)
      ctx.save()

      ctx.rotate(deg)
      ctx.moveTo(0, -R)
      ctx.lineTo(0, R)

      ctx.moveTo(ballR, balls[i].y)
      ctx.arc(balls[i].x, balls[i].y, ballR, 0, Math.PI * 2)
      ctx.restore()
    }
    function draw() {
      ctx.beginPath()
      ctx.arc(0, 0, R, 0, Math.PI * 2)
      ctx.closePath()
      for (let i = 0; i < 9; i++) {
        drawSinLine((i * Math.PI) / 9, i)
      }
      ctx.stroke()
    }

    function updateInfo() {
      for (let item of balls) {
        if (item.y < -R) {
          item.v = ballV
        } else if (item.y > R) {
          item.v = -ballV
        }
        item.y += item.v
      }
    }
    draw()

    window.onclick = function() {
      loop()
    }

    // loop()
    function loop() {
      updateInfo()
      draw()
      ctx.fillStyle = 'blue'
      requestAnimationFrame(loop)
    }
  }
}
</script>

<style lang="less" scoped>
html,
body {
  width: 100%;
}

.page_main {
  margin: 0 0.2rem;
  canvas {
    width: 100%;
    background: #333;
  }
}
</style>
